package yams.resource.impl;

import javafx.util.Callback;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import yams.callback.IdCallback;
import yams.common.constants.BillStatusEnum;
import yams.common.constants.BillTypeEnum;
import yams.common.constants.ContractStatusEnum;
import yams.common.constants.RequestStatusEnum;
import yams.domain.*;
import yams.resource.ICleanResource;
import yams.resource.JsonCommonResource;
import yams.response.JsonResponse;
import yams.response.Response;
import yams.service.*;
import yams.service.impl.DefaultCommonService;
import yams.utils.BreezeeUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;

/**
 * Created by LX on 2017/7/24.
 */
@SuppressWarnings("unchecked")
@RestController
@RequestMapping("/clean")
public class DefaultCleanResource extends JsonCommonResource implements ICleanResource{
    private ICommonService cleanCallService;
    @Resource
    private IUserService userService;
    @Resource
    private IContractService contractService;
    @Resource
    private IHouseService houseService;
    @Resource
    private IBillService billService;
    @Resource
    private IdCallback idCallback;

    @RequestMapping(value = "/", method = RequestMethod.POST)
    @Override
    public Response<CleanEntity> page(@RequestBody CleanEntity cleanEntity) {
        //日期查找bug---格式化日期类型
        try {
            if (cleanEntity.getProperties().get("_startDate") != null) {
                cleanEntity.getProperties().put("issueTime_gt", BreezeeUtils.DATE_FORMAT_SHORT.parse(cleanEntity.getProperties().get("_startDate").toString()));
            }
            if (cleanEntity.getProperties().get("_endDate") != null) {
                cleanEntity.getProperties().put("issueTime_le", BreezeeUtils.DATE_FORMAT_SHORT.parse(cleanEntity.getProperties().get("_endDate").toString()));
            }
        } catch (ParseException e) {
            //e.printStackTrace();
        }
        return _pageAll(cleanCallService, cleanEntity);
    }

    @RequestMapping(value = "/pageWithHandlerName", method = RequestMethod.POST)
    @Override
    public Response<CleanEntity> page_name(@RequestBody CleanEntity cleanEntity) {
        //获得所有的RepairCallEntity
        JsonResponse<CleanEntity> r = _pageAll(cleanCallService, cleanEntity);
        List<CleanEntity> clean= (List<CleanEntity>) r.getRows();
        /*for(int i=0;i<clean.size();i++){
            String handerId=clean.get(i).getHandleUser();
            //通过handleId获得用户具体信息
            if(handerId==null || handerId==""){
                clean.get(i).setHandleUserName("无");
            }else{
                UserEntity user=userService.findByCode(handerId);
                if(user!=null){
                    clean.get(i).setHandleUserName(user.getName());
                }else{
                    clean.get(i).setHandleUserName("无");
                }
            }
        }*/
        return JsonResponse.build(clean);
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    @Override
    public Response<CleanEntity> findById(@PathVariable String id) {
        return _findOne(cleanCallService, id, 0);
    }

    @RequestMapping(value = "/code/{code}", method = RequestMethod.GET)
    @Override
    public Response<CleanEntity> findByCode(@PathVariable String code) {
        return _findOne(cleanCallService, code, 1);
    }

    @RequestMapping(value = "/", method = RequestMethod.PUT)
    @Override
    public Response<CleanEntity> save(@RequestBody CleanEntity cleanEntity) {
        cleanEntity.setIssueTime(new Date());
        if(!StringUtils.isEmpty(cleanEntity.getMediaIds())){
            String[] cleanImgs=cleanEntity.getMedias();
            if(cleanImgs.length==1){
                cleanEntity.setAImage(cleanImgs[0]);
            }
            if(cleanImgs.length==2){
                cleanEntity.setAImage(cleanImgs[0]);
                cleanEntity.setBImage(cleanImgs[1]);
            }
            if(cleanImgs.length==3){
                cleanEntity.setAImage(cleanImgs[0]);
                cleanEntity.setBImage(cleanImgs[1]);
                cleanEntity.setCImage(cleanImgs[2]);
            }
            if(cleanImgs.length==4){
                cleanEntity.setAImage(cleanImgs[0]);
                cleanEntity.setBImage(cleanImgs[1]);
                cleanEntity.setCImage(cleanImgs[2]);
                cleanEntity.setDImage(cleanImgs[3]);
            }
            if(cleanImgs.length==5){
                cleanEntity.setAImage(cleanImgs[0]);
                cleanEntity.setBImage(cleanImgs[1]);
                cleanEntity.setCImage(cleanImgs[2]);
                cleanEntity.setDImage(cleanImgs[3]);
                cleanEntity.setEImage(cleanImgs[4]);
            }
        }
        return _saveInfo(cleanCallService, cleanEntity, (Callback<CleanEntity, Object>) param -> {
            if (param.getCode() == null)
                param.setCode(System.currentTimeMillis() + "");
            param.setName(LocalDate.now()+"_"+param.getIssueUserName()+"_"+param.getType()+"保洁");
            return null;
        });
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @Override
    public Response<CleanEntity> delete(@PathVariable String id) {
        return _delete(cleanCallService, id);
    }

    @Override
    public void initService() {
        if (cleanCallService == null)
            cleanCallService = new DefaultCommonService("cleanRepository");
    }


    @RequestMapping(value = "/handle", method = RequestMethod.POST)
    @Override
    public Response<CleanEntity> handleCleanCall(@RequestBody CleanEntity cleanEntity){
        CleanEntity old = (CleanEntity) cleanCallService.findById(cleanEntity.getId());
        old.setHandleTime(new Date());
        old.setResult(cleanEntity.getResult());
        old.setCleanFee(cleanEntity.getCleanFee());
        old.setStatus(RequestStatusEnum.PROCESSED.getValue());

        UserEntity user = userService.findById(old.getIssueUser());
        if(user != null){
            ContractEntity contractCondition = new ContractEntity();
            contractCondition.getProperties().put("status", ContractStatusEnum.EXECUTING.getValue());
            contractCondition.getProperties().put("user_id_obj_ae",user.getId());
            List<ContractEntity> contractList = contractService.listAll(contractCondition);
            if(!CollectionUtils.isEmpty(contractList) && contractList.size() == 1){
                ContractEntity contract = contractList.get(0);
                HouseEntity house = houseService.findById(contract.getHouseId());

                BillEntity bill = new BillEntity();
                bill.setCode("4" + old.getCode());
                bill.setName(old.getName());
                bill.setCreatedDate(new Date());
                bill.setRemark(cleanEntity.getRemark());
                bill.setTotalAmount(cleanEntity.getCleanFee());
                bill.setActualAmount(cleanEntity.getCleanFee());
                bill.setStatus(BillStatusEnum.UNPAID.getValue());
                bill.setContract(contract);
                bill.setHouse(house);
                bill.setUser(user);
                bill.setType(BillTypeEnum.CLEAN.getValue());
                billService.getRepository().saveEntity(bill, new Callback[]{idCallback});
            }
        }

        return _saveInfo(cleanCallService, old);
    }
}
